const gulp = require("gulp");
const server = require("gulp-webserver");
const sass = require("gulp-sass");
const autoprefixer = require("gulp-autoprefixer");
const path=require("path");
const fs=require("fs");
const url=require("url");
const data=require("./src/data/data.json");


gulp.task("devscss", function () {
    return gulp.src("./src/scss/*.scss")
        .pipe(sass())
        .pipe(autoprefixer({
            browers: ["last 2 versions"]
        }))
        .pipe(gulp.dest("./src/css"))
})
gulp.task("watch", function () {
    return gulp.watch("./src/scss/*.scss", gulp.series("devscss"));
})
gulp.task("devserver", function () {
    return gulp.src("src")
        .pipe(server({
            port: 9088,
            open: true,
            livereload: true,
            middleware:function(req,res,next){
                var pathname=url.parse(req.url,true).pathname;
                if(pathname==="/favicon.ico"){
                    return res.end("");
                }
                
                if(pathname==="/api/getUid"){
                    res.end(JSON.stringify({code:1,uid:"123"}))
                }else if(pathname==="/api/getlist"){
                    res.end(JSON.stringify({code:2,data,msg:"列表"}))
                }else{
                    pathname=pathname==="/"?"index.html":pathname;
                    res.end(fs.readFileSync(path.join(__dirname,"src",pathname)));
                }
            }
        }))
})
gulp.task("dev", gulp.series("devscss", "devserver", "watch"))